import json
import os
from core.utils.error_handler import safe_json_load, safe_json_save, ErrorHandler
from core.utils.logger import error, warning, debug

class DataManager:
    def __init__(self, data_dir=None):
        # 如果没有指定数据目录，使用包内绝对路径
        if data_dir is None:
            # 获取当前文件的绝对路径
            current_file = os.path.abspath(__file__)
            # 从 core/services/data_manager.py 回到 alibaba 包根目录
            package_root = os.path.dirname(os.path.dirname(os.path.dirname(current_file)))
            # 拼接 data 目录
            data_dir = os.path.join(package_root, "data")
        
        self.data_dir = data_dir
        self._ensure_data_dir()
        self._ensure_data_files()
    
    def _ensure_data_dir(self):
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
    
    def _ensure_data_files(self):
        files = ["users.json", "products.json", "orders.json"]
        for file in files:
            filepath = os.path.join(self.data_dir, file)
            if not os.path.exists(filepath):
                with open(filepath, 'w', encoding='utf-8') as f:
                    json.dump([], f, ensure_ascii=False, indent=2)
    
    def _get_file_path(self, filename):
        return os.path.join(self.data_dir, filename)
    
    def load_data(self, filename):
        filepath = self._get_file_path(filename)
        debug(f"加载数据文件: {filename}")
        
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                data = json.load(f)
                debug(f"成功加载数据文件: {filename}, 记录数: {len(data) if isinstance(data, list) else 'N/A'}")
                return data
        except FileNotFoundError:
            warning(f"数据文件不存在: {filename}, 返回空列表")
            return []
        except json.JSONDecodeError as e:
            error(f"JSON解析错误: {filename} - {str(e)}")
            return []
        except PermissionError as e:
            error(f"文件权限错误: {filename} - {str(e)}")
            return []
        except Exception as e:
            ErrorHandler.log_exception(e, f"加载数据文件 {filename}")
            return []
    
    def save_data(self, filename, data):
        filepath = self._get_file_path(filename)
        debug(f"保存数据文件: {filename}")
        
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(filepath), exist_ok=True)
            
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            debug(f"成功保存数据文件: {filename}")
            return True
        except PermissionError as e:
            error(f"文件权限错误: {filename} - {str(e)}")
            return False
        except OSError as e:
            error(f"文件系统错误: {filename} - {str(e)}")
            return False
        except Exception as e:
            ErrorHandler.log_exception(e, f"保存数据文件 {filename}")
            return False
    
    def load_users(self):
        return self.load_data("users.json")
    
    def save_users(self, users_data):
        self.save_data("users.json", users_data)
    
    def load_products(self):
        return self.load_data("products.json")
    
    def save_products(self, products_data):
        self.save_data("products.json", products_data)